package com.test.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class CacheUtils {
    @Resource
    StringRedisTemplate template;
    public void deleteFromCache(String key){
        Set<String> keys = Optional.ofNullable(template.keys(key)).orElse(Collections.emptySet());
        template.delete(keys);
    }
    public <T> List<T> getListFromCache(String key,Class<T> itmetype){
        String json = template.opsForValue().get(key);
        if(json == null ) return  null;
        return JSONArray.parseArray(json, itmetype);
    }
    public <T> T getDataFromCache(String key,Class<T> itmetype){
        String json = template.opsForValue().get(key);
        if(json == null ) return  null;
        return JSONObject.parseObject(json, itmetype);
    }

    public <T> void  savedataToCache(String key,T data,int expire){
        template.opsForValue().set(key, JSONObject.from(data).toJSONString(),expire, TimeUnit.MILLISECONDS);

    }
    public <T> void saveListToCache(String key,List<T> list,int expire){
        template.opsForValue().set(key, JSONArray.from(list).toJSONString(),expire, TimeUnit.MILLISECONDS);

    }
}
